package org.ww.cart.interceptor;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.ww.cart.to.UserInfoTo;
import org.ww.common.constant.AuthConstant;
import org.ww.common.constant.CartConstant;
import org.ww.common.vo.MemberRespVo;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @program: gmall
 * @description: 购物车拦截器
 * 在执行目标方法之前，判断用户的登录状态，并封装传递给controller目标请求
 * 在web配置中将拦截器加进去
 * @author: ww
 * @create: 2024-05-17 13:23
 **/
@Component
public class CartInterceptor implements HandlerInterceptor {

    public static ThreadLocal<UserInfoTo> threadLocal = new InheritableThreadLocal<>();

    /**
     * 目标方法controller拦截前执行
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfoTo userInfoTo = new UserInfoTo();

        HttpSession session = request.getSession();
        MemberRespVo memberRespVo = (MemberRespVo) session.getAttribute(AuthConstant.LONGINUSER);
        //如果当前用户登录了，设置userId
        if(ObjectUtils.isNotEmpty(memberRespVo)){
            userInfoTo.setUserId(memberRespVo.getId());
        }
        Cookie[] cookies = request.getCookies();
        if(null != cookies && cookies.length > 0){
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if(CartConstant.USERKEY.equals(name)){
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setIsTempUser(Boolean.FALSE);
                    break;
                }
            }
        }

        //如果没有临时用户就分配一个临时用户（这里不管有没有登录都会分配一个userKey）
        if(StringUtils.isBlank(userInfoTo.getUserKey())){
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);
        }
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 方法执行后调用，让浏览器感知到并且存储cookie信息
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfoTo userInfoTo = threadLocal.get();
        //如果是临时用户，将user-key存储在cookie中
        if(userInfoTo.getIsTempUser()){
            Cookie cookie = new Cookie(CartConstant.USERKEY, userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_KEY_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
